home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 902 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  55 lines

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: pseudo-random numbers
  5. Date: Wed, 10 Jan 96 00:14:37 GMT
  6. Organization: none
  7. Message-ID: <821232877snz@genesis.demon.co.uk>
  8. References: <17709D420S86.JJSTEP00@ukcc.uky.edu>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <17709D420S86.JJSTEP00@ukcc.uky.edu>
  15.            JJSTEP00@ukcc.uky.edu "Jason Stephenson" writes:
  16.  
  17. >I know what the c.l.c. FAQ says about pseudo-random numbers, so I wonder why
  18. >I seem to get "better" results with "rand() % n + 1" than I get when I use
  19. >"n * rand() / RAND_MAX + 1"  Am I missing some parenthesis or something?
  20.  
  21. Your code might overflow when calculating n * rand(). Use the versions in
  22. section 13.16 of the FAQ, they don't have this problem. You could also try
  23. the following which should give a even distribution:
  24.  
  25.  
  26. #include <stdlib.h>
  27.  
  28. int randrange(int range)
  29.  
  30. {
  31.     const int threshold = RAND_MAX - RAND_MAX % range;
  32.     const int divisor = RAND_MAX / range;
  33.     int     randval;
  34.  
  35.     while ((randval = rand()) >= threshold)
  36.         ;
  37.  
  38.     return randval / divisor;
  39. }
  40.  
  41.  
  42. >Oh yeah, and I usually call "srand(clock())" once in the initialization of
  43. >my program.
  44.  
  45. Bad idea. On some systems clock() returns values that start at zero at
  46. program startup resulting in a high chance of the same seed on repeated
  47. runs of the program. time() is better (although you don't strictly know
  48. what type time_t is).
  49.  
  50. -- 
  51. -----------------------------------------
  52. Lawrence Kirby | fred@genesis.demon.co.uk
  53. Wilts, England | 70734.126@compuserve.com
  54. -----------------------------------------
  55.